#include <stdlib.h>
#include <stdio.h>
#include <rthw.h>
#include <rtthread.h>
#include "user_mb_app.h"

#define thread_ModbusSlavePoll_Prio 10
static rt_uint8_t thread_ModbusSlavePoll_stack[512];
struct rt_thread thread_ModbusSlavePoll;

extern USHORT usSRegHoldBuf[S_REG_HOLDING_NREGS];

static void prvvRegHoldInit(void)
{
    usSRegHoldBuf[0x0000] = 0x0002;
    usSRegHoldBuf[0x0001] = 0x0640;
    usSRegHoldBuf[0x0002] = 0x0030;
    usSRegHoldBuf[0x0003] = 0x0002;

    usSRegHoldBuf[0x0010] = 0x0001;
    usSRegHoldBuf[0x0011] = 0x3800;
    usSRegHoldBuf[0x0012] = 0x0001;
    usSRegHoldBuf[0x0013] = 0x0000;
    usSRegHoldBuf[0x0014] = 0x0801;

    usSRegHoldBuf[0x0030] = 0x0000;
    usSRegHoldBuf[0x0031] = 0x000e;
    usSRegHoldBuf[0x0032] = 0x0000;
    usSRegHoldBuf[0x0033] = 0x0000;
    usSRegHoldBuf[0x0034] = 0x0000; //传感器1高16位
    usSRegHoldBuf[0x0035] = 0x00fd; //传感器1低16位
    usSRegHoldBuf[0x0036] = 0x4000;
    usSRegHoldBuf[0x0037] = 0x0000; //低报
    usSRegHoldBuf[0x0038] = 0x0064;
    usSRegHoldBuf[0x0039] = 0x0000; //高报
    usSRegHoldBuf[0x003a] = 0x0154;
    usSRegHoldBuf[0x003b] = 0x0000; //量程
    usSRegHoldBuf[0x003c] = 0x04b0;
    usSRegHoldBuf[0x003d] = 0x0000; //当前真实温度，校准用
    usSRegHoldBuf[0x003e] = 0x0000;
    usSRegHoldBuf[0x003f] = 0x0000;

    usSRegHoldBuf[0x005c] = 0x0000;

    usSRegHoldBuf[0x0060] = 0x0100;
    usSRegHoldBuf[0x0061] = 0x000e;
    usSRegHoldBuf[0x0062] = 0x0000;
    usSRegHoldBuf[0x0063] = 0x0000;
    usSRegHoldBuf[0x0064] = 0x0000; //传感器2高16位
    usSRegHoldBuf[0x0065] = 0x02b3; //传感器2低16位
    usSRegHoldBuf[0x0066] = 0x4002;
    usSRegHoldBuf[0x0067] = 0x0000; //低报
    usSRegHoldBuf[0x0068] = 0x00c8;
    usSRegHoldBuf[0x0069] = 0x0000; //高报
    usSRegHoldBuf[0x006a] = 0x01f4;
    usSRegHoldBuf[0x006b] = 0x0000; //量程
    usSRegHoldBuf[0x006c] = 0x03e8;
    usSRegHoldBuf[0x006d] = 0x0000; //当前真实温度，校准用
    usSRegHoldBuf[0x006e] = 0x0000;
    usSRegHoldBuf[0x006f] = 0x0000;

    usSRegHoldBuf[0x0080] = 0x0000; //传感器1数据
    usSRegHoldBuf[0x0081] = 0x00fd;
    usSRegHoldBuf[0x0082] = 0x4000; //小数位、单位、状态
    usSRegHoldBuf[0x0083] = 0x0000; //传感器2数据
    usSRegHoldBuf[0x0084] = 0x02b0;
    usSRegHoldBuf[0x0085] = 0x4002; //小数位、单位、状态

    usSRegHoldBuf[0x008c] = 0x0000;
}

/**
* \brief Modbus从机轮询入口
*/
void thread_entry_ModbusSlavePoll(void *parameter)
{
    prvvRegHoldInit();

    //地址1 端口选择Port1 即Uart1 9600 8 N 1
    eMBInit(MB_RTU, 0x01, 1, 9600, MB_PAR_NONE);
    eMBEnable();
    while (1)
    {
        eMBPoll();
    }
}

void test_modbus(void)
{
    rt_thread_init(&thread_ModbusSlavePoll, "MBSlavePoll",
                   thread_entry_ModbusSlavePoll, RT_NULL, thread_ModbusSlavePoll_stack,
                   sizeof(thread_ModbusSlavePoll_stack), thread_ModbusSlavePoll_Prio,
                   5);
    rt_thread_startup(&thread_ModbusSlavePoll);
}
